import React, { useEffect, useRef } from 'react';
import flvjs from 'flv.js';
import { history } from 'umi';
type Props = {}

const liveDetail = (props: Props) => {
    const flvPlayerRem: any = useRef(null);
    // let flvPlayer: flvjs.Player;
    let count = 0;

    const initFlv = () => {
        let videoElement: any = document.getElementById('videoElement');
        if (!videoElement) {
            console.log('视频元素未找到');
            return;
        }
        let flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: 'http://127.0.0.1:8000/live/ymj.flv'
        });
        flvPlayer.attachMediaElement(videoElement)
        flvPlayer.load();
        flvPlayer.play();
        flvPlayerRem.current = flvPlayer;
        //如果有缓存，有延迟的情况下，如何做到实时更新？追帧
        videoElement.addEventListener('progress', () => {
            console.log('进行中');
            let end = flvPlayer.buffered.end(0);//全部的位置(推)
            //追帧位置 = 全部的位置(推) - 当前的播放位置(拉);
            let chase = end - flvPlayer.currentTime;
            console.log(chase, '需要追帧的位置');
            //判断追帧位置>10||判断追帧位置<0{赋值当前位置，相当于做跳帧的动作}
            if (chase > 5 || chase < 0) {
                //这里rtmp tcp协议传输有延迟15左右;
                flvPlayer.currentTime = flvPlayer.buffered.end(0) - 1;
                return;
            }
            //追帧倍速，调整倍速，追帧时间大于1s就进行倍速
            if (chase > 1) {
                videoElement.playbackRate = 1.5;
            } else {
                videoElement.playbackRaate = 1;
            }
        });

        //断流重连的操作 错误监听的一个事件

        flvPlayer.on(flvjs.Events.ERROR, () => {
            if (count < 5) {
                console.log('error 断流重连的操作', count);
                //这里需要销毁当前的播放器
                flvPlayer.pause();
                //重新连接的事情
                setTimeout(async () => {
                    count++;
                    initFlv();
                }, 3000)
            } else {
                console.log('连接超时，请重新进入');
                history.push('/Lbordercast')
            }
        });
    };

    useEffect(() => {
        //progress 监听进展事件
        if (flvjs.isSupported()) {
            initFlv();
        }
        return () => {
            //在组件里面做播放器的销毁
            if (flvPlayerRem.current) {
                flvPlayerRem.current.pause();
                flvPlayerRem.current.unload();
                flvPlayerRem.current.detachMediaElement();
                flvPlayerRem.current.destroy();
                flvPlayerRem.current = null;
            }
        }


    }, []);

    // const handleVideo = () => {
    //     if (flvPlayer && flvPlayer.duration) {
    //         flvPlayer.play();
    //     }
    // }
    return (
        <div>
            <video
                id="videoElement"
                controls
                style={{ width: '100%', height: '100%' }}
            ></video>
            {/* <button onClick={handleVideo}>开播</button> */}
        </div>
    )
}

export default liveDetail

